package com.juyu.miliao.authentication.service;

import com.juyu.miliao.authentication.dao.mysql.OpenApiStatusDao;
import com.juyu.miliao.authentication.dao.mysql.VersionHistoryDao;
import com.juyu.miliao.authentication.domain.Version;
import com.juyu.miliao.authentication.domain.VersionVO;
import com.juyu.miliao.common.constant.PhoneSystemConstant;
import com.juyu.miliao.common.domain.OpenApiStatus;
import com.juyu.miliao.common.util.CommonUtil;
import com.juyu.miliao.common.util.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: 卜加超
 * @Date: 2019/4/3 10:27
 * @Description:
 */
@Service
public class VersionService {

    /**
     * 下载落地页 http://sw.goliaoyou.com/ground/ground001/index.html?id=channel
     */
    private static final String DOWNLOAD_PAGE = "http://sw.goliaoyou.com/ground/ground001/index.html?id=";

    private static final String DOWNLOAD_URL_ANDROID = "http://sw.goliaoyou.com/apk/huami_";

    private static final String ANDROID_POSTFIX = ".apk";

    private static final String DEFAULT_STRING = "default_";


    @Resource
    private VersionHistoryDao versionHistoryDao;

    @Resource
    private OpenApiService openApiService;

    @Resource
    private OpenApiStatusDao openApiStatusDao;


    /**
     * 版本按.分割
     *
     * @param forceVersion 版本
     * @return List<Integer>
     */
    private static List<Integer> splitVersionString(String forceVersion) {
        List<Integer> list = new ArrayList<>();
        if (!StringUtils.isEmpty(forceVersion)) {
            String[] adrStrings = forceVersion.split("\\.");
            if (adrStrings.length >= 3) {
                list.add(CommonUtil.null2Int(adrStrings[0]));
                list.add(CommonUtil.null2Int(adrStrings[1]));
                list.add(CommonUtil.null2Int(adrStrings[2]));
            }
        }
        return list;
    }

    /**
     * 默认包更新地址=地址+_+appPackageId
     *
     * @param phoneSystem  phoneSystem
     * @param appPackageId appPackageId
     * @return String
     */
    private static String getDownloadUrl(int phoneSystem, String appPackageId, String channel) {
        String url;
        if (phoneSystem == PhoneSystemConstant.ANDROID) {
            url = DOWNLOAD_URL_ANDROID + DEFAULT_STRING + appPackageId + ANDROID_POSTFIX;
        } else if ("huami_appstore".equals(channel)) {
            url = "https://itunes.apple.com/cn/app/id1439419255?mt=8";
        } else {
            url = DOWNLOAD_PAGE + DEFAULT_STRING + appPackageId;
        }
        return url;
    }

    /**
     * 比较是否需要更新
     *
     * @param ids     待比较版本
     * @param version 数据库版本
     * @return boolean　true-需要  false-不需要
     */
    private boolean compare(String[] ids, String version) {
        List<Integer> forceIds = splitVersionString(version);
        int var;
        int forceVar;
        boolean flag = true;
        for (int i = 0; i < 3; i++) {
            var = CommonUtil.null2Int(ids[i]);
            forceVar = forceIds.get(i);
            if (var > forceVar) {
                flag = false;
                break;
            }

            if (var == forceVar) {
                if (i == 2) {
                    flag = false;
                }
                continue;
            }

            //比forceVar小
            break;
        }

        return flag;
    }

    /**
     * 比较版本,并返回最新版本
     *
     * @param ids         version 以 . 分隔
     * @param phoneSystem 手机系统
     * @return ForceVersionVO
     */
    public VersionVO compareVersion(String[] ids, int phoneSystem, String channel, String appPackageId, String versionNum) {

        VersionVO vo = new VersionVO();
        //更新地址
        vo.setUrl(getDownloadUrl(phoneSystem, appPackageId, channel));
        //判断是否审核
        Boolean isAudit = openApiService.getForwardAudit(appPackageId, String.valueOf(phoneSystem), versionNum, channel);
        vo.setIsAudit(isAudit);

        Version forceVersionHistory = versionHistoryDao.getLastForceUpdatingVersion(phoneSystem, appPackageId);
        if (forceVersionHistory == null) {
            vo.setForceUpdating(false);
        } else {
            String forceVersion = forceVersionHistory.getVersion();
            Boolean flag = compare(ids, forceVersion);
            vo.setForceUpdating(flag);
        }

        Version newestVersionHistory = versionHistoryDao.getNewestVersion(phoneSystem, appPackageId);
        if (newestVersionHistory == null) {
            vo.setHaveUpdating(false);
            return vo;
        } else {
            boolean flag = compare(ids, newestVersionHistory.getVersion());
            vo.setHaveUpdating(flag);
            String s = newestVersionHistory.getDetail();
            s = s.replaceAll("\\|", "\n");
            vo.setDetail(s);
            vo.setType(phoneSystem);
            vo.setVersion(newestVersionHistory.getVersion());
        }

        return vo;
//        return JSON.toJSONString(vo);
    }

    /**
     * 比较版本,并返回最新版本
     * @param ip
     * @param ids         version 以 . 分隔
     * @param phoneSystem 手机系统
     * @return ForceVersionVO
     */
    public Boolean compareVersion(String ip,String[] ids, int phoneSystem, String channel, String appPackageId, String versionNum) {

        //判断是否审核
        Boolean isAudit = openApiService.getForwardAudit(appPackageId, String.valueOf(phoneSystem), versionNum, channel);

//        OpenApiStatus openApiStatus = openApiStatusDao.getOpenApiStatus(versionNum, phoneSystem, appPackageId, channel);
//        if(openApiStatus!=null){
//            if(openApiStatus.getIsUsaIp()==1){
//                String country= QueryIpRegion.queryIP(ip);
//                if(country!=null && "美国".equals(country)){
//                    return true;
//                }
//            }
//        }
        return isAudit;
    }

}
